package jp.co.systemi.asp.workflow.peer;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import jp.co.systemi.asp.workflow.data.Apply;
import jp.co.systemi.asp.workflow.data.ApplyMeta;
import jp.co.systemi.asp.workflow.data.Common;
import jp.co.systemi.asp.workflow.data.Group;
import jp.co.systemi.asp.workflow.data.GroupMeta;
import jp.co.systemi.asp.workflow.data.User;
import jp.co.systemi.asp.workflow.data.UserMeta;

import org.datanucleus.util.StringUtils;
import org.slim3.datastore.Datastore;

import com.google.appengine.api.datastore.Key;

public class ApplyPeer {

    private static final Logger log = Logger.getLogger(ApplyPeer.class
            .getName());

    // TODO：同じloginIdで、複数役割の承認ルートの対応
    // 　組織選択が必要かな
    public static List<Apply> getApproveSummaries(String loginId) {
        ApplyMeta am = ApplyMeta.get();
        List<Apply> retList = new ArrayList<Apply>();
        //　まず承認者で検索
        List<Apply> applyData = Datastore.query(am).filter(
                am.approver.equal(loginId)).sort(am.summaryId.asc).asList();
        int i = 0;
        next_apply:
        for (Apply apply : applyData) {
            if (apply.getStatus().equals(Common.APPLY_STATUS.REJECTED)) {
                continue;
            }
            if (apply.getStatus().equals(Common.APPLY_STATUS.CANCELED)) {
                continue;
            }
            // 前の承認者が承認済み、次の承認者は未承認であること
            List<Apply> approvers = Datastore.query(am).filter(
                    am.summaryId.equal(apply.getSummaryId())).sort(am.seq.asc)
                    .asList();
            int j = 0;
            for (Apply approver : approvers) {
                j++;
                if (approver.getApprover().equals(loginId)) {
                    if (j > 1
                            && !approvers.get(j - 2).getStatus().equals(
                                    Common.APPLY_STATUS.APPROVED)) {
                        log.info("前の承認者が承認されるまで、しばらくお待ちください。");
                        continue next_apply;
                    }
                    if (j < approvers.size()
                            && !approvers.get(j).getStatus().equals(
                                    Common.APPLY_STATUS.APPLYING)) {
                        log.info("も次の承認者が承認済みですよ。");
                        continue next_apply;
                    }
                }
            }
            apply = Datastore.query(am).filter(
                    am.id.equal(apply.getSummaryId())).asSingle();
            // if summary is
            if (apply.getStatus().equals(Common.APPLY_STATUS.CANCELED)) {
                continue;
            }
            if (apply.getStatus().equals(Common.APPLY_STATUS.ACCEPTED)) {
                continue;
            }
            if (apply.getStatus().equals(Common.APPLY_STATUS.APPROVED)) {
                continue;
            }
            if (apply.getStatus().equals(Common.APPLY_STATUS.REJECTED)) {
                continue;
            }
            apply.setSeq(++i);
            // 申請者名
            UserMeta um = UserMeta.get();
            User user = Datastore.query(um).filter(
                    um.loginId.equal(apply.getApplyee())).asSingle();
            apply.setApplyeeName(UserPeer.getName(user));
            retList.add(apply);
        }
        return retList;
    }

    /**
     * 申請サマリ一覧を取得する
     *
     * @param pm
     * @param loginId
     * @return
     */
    public static List<Apply> getApplySummaries(String loginId,
            Boolean incApporved) {
        List<Apply> retList = new ArrayList<Apply>();
        ApplyMeta am = ApplyMeta.get();
        List<Apply> applyData = Datastore.query(am).filter(
                am.applyee.equal(loginId)).sort(am.id.asc).asList();
        int i = 0;
        for (Apply apply : applyData) {
            if (!StringUtils.isEmpty(apply.getApprover())) {
                continue;
            }
            if (!incApporved
                    && apply.getStatus().equals(Common.APPLY_STATUS.APPROVED)) {
                continue;
            }
            if (apply.getStatus().equals(Common.APPLY_STATUS.ACCEPTED)) {
                continue;
            }
            if (apply.getStatus().equals(Common.APPLY_STATUS.CANCELED)) {
                continue;
            }
            // 申請者名
            UserMeta um = UserMeta.get();
            User user = Datastore.query(um).filter(
                    um.loginId.equal(apply.getApplyee())).asSingle();
            apply.setApplyeeName(UserPeer.getName(user));

            apply.setSeq(++i);
            retList.add(apply);
        }
        return retList;
    }

    /**
     * 指定申請番号の申請レコード一覧を取得する
     *
     * @param summaryKey
     * @return
     */
    public static List<Apply> getApplies(Key summaryKey) {

        ApplyMeta am = ApplyMeta.get();
        List<Apply> applies = Datastore.query(am).filter(
                am.summaryId.equal(summaryKey)).sort(am.seq.asc).asList();

        UserMeta um = UserMeta.get();
        GroupMeta gm = GroupMeta.get();
        for (Apply apply : applies) {
            // 承認者名前
            User user = Datastore.query(um).filter(
                    um.loginId.equal(apply.getApprover())).asSingle();
            if (user != null) {
                apply.setApproverName(UserPeer.getName(user));
            } else {
                return null;
            }
            // 所属
            Group group = Datastore.query(gm).filter(
                    gm.code.equal(apply.getApproverGroupCode())).asSingle();
            if (group != null) {
                apply.setApproverGroupName(group.getName());
            } else {
                return null;
            }
        }
        return applies;
    }
}
